1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
use super::*;

/// A lambda function
#[derive(Clone, Eq)]
pub struct Lambda {
    /// The symbol being abstracted over
    arg: SymbolId,
    /// The result of this lambda function
    result: ValId,
    /// The type of this lambda function
    ty: ValId,
    /// The free variable set of this lambda function
    fv: SymbolSet,
    /// This lambda function's (cached) hash-code
    code: u64,
    /// This lambda function's local constraint-set
    constraints: Constraints,
    /// This lambda function's internal constraints
    internal: Constraints,
}

impl PartialEq for Lambda {
    fn eq(&self, other: &Lambda) -> bool {
        match (self.variance(), other.variance()) {
            (None, None) => self.arg.ty() == other.arg.ty() && self.result == other.result,
            (Some(l), Some(r)) => l == r && self.arg == other.arg && self.result == other.result,
            _ => false,
        }
    }
}

impl Debug for Lambda {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        fmt.debug_struct("Lambda")
            .field("arg", &self.arg)
            .field("result", &self.result)
            .finish()
    }
}

impl Hash for Lambda {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        if self.is_const_fn() {
            self.arg.ty().hash(hasher)
        } else {
            self.arg.hash(hasher);
        }
        self.result.hash(hasher);
    }
}

impl Lambda {
    /// Construct a new lambda function
    pub fn try_new(arg: SymbolId, result: ValId) -> Result<Lambda, Error> {
        let (linearity, fv, internal, constraints) = Self::make_constraints(&arg, &result);
        let ty = Pi::try_new(arg.clone(), result.ty().clone(), linearity)
            .expect(".ty() should always yield a type!")
            .into_valid();
        let mut result = Lambda {
            arg,
            result,
            ty,
            fv,
            code: 0,
            constraints,
            internal,
        };
        result.update_code();
        Ok(result)
    }
    /// Construct a constant lambda function
    pub fn constant(arg_ty: ValId, result: ValId) -> Result<Lambda, Error> {
        let arg = SymbolId::param(arg_ty)?;
        Self::try_new(arg, result)
    }
    /// Get the result type of this function
    pub fn result(&self) -> &ValId {
        &self.result
    }
    /// Get the argument this function is abstracted over
    pub fn arg(&self) -> &SymbolId {
        &self.arg
    }
    /// Get the argument type of this function
    ///
    /// Equivalent to `self.arg().ty()`
    pub fn arg_ty(&self) -> &ValId {
        self.arg.ty()
    }
    /// Get the pi type of this function
    pub fn pi_ty(&self) -> &Pi {
        match self.ty().as_enum() {
            ValueEnum::Pi(p) => p,
            value => panic!("Non pi type {:?} for lambda function {:?}", value, self),
        }
    }
    /// Get the functional linearity of this function
    pub fn fun_lin(&self) -> FunctionalLinearity {
        self.pi_ty().fun_lin()
    }
    /// Construct the identity function over a given type
    ///
    /// Returns an error if `ty` is not a type.
    pub fn id(ty: ValId) -> Result<Lambda, Error> {
        let arg = SymbolId::param(ty)?;
        let result = Self::try_new(arg.clone(), Symbol::from(arg).into_valid())?;
        debug_assert_eq!(result.fv(), result.arg.def_fv());
        debug_assert!(!result.is_const_fn());
        Ok(result)
    }
    /// Get the variance of this lambda function's result with respect to it's argument
    #[inline]
    pub fn variance(&self) -> Option<Dependency> {
        //TODO: benchmark whether storing this is a better idea
        self.result.fv().get(&self.arg)
    }
    /// Whether this lambda function is a constant function
    #[inline]
    pub fn is_const_fn(&self) -> bool {
        //TODO: benchmark whether storing this is a better idea
        !self.result.fv().contains(&self.arg)
    }
    /// Get the internal constraints of this lambda function
    #[inline]
    pub fn internal_constraints(&self) -> &Constraints {
        &self.internal
    }
    /// Update the hash-code of this lambda function
    ///
    /// Should be a no-op for any publically accessible lambda function
    #[inline]
    fn update_code(&mut self) {
        let mut hasher = Self::get_hasher();
        let arg_code = if self.is_const_fn() {
            self.arg.ty().code()
        } else {
            self.arg.code()
        };
        arg_code.hash(&mut hasher);
        self.result.hash(&mut hasher);
        self.code = hasher.finish();
    }
    #[allow(clippy::too_many_arguments)]
    fn handle_cross(
        inner: &ValId,
        outer: &ValId,
        relationship: Relationship,
        dep_ty: Dependency,
        constraints: &mut Constraints,
        internal: &mut Constraints,
        linearity: &mut Linearity,
        call_usage: &mut Usage,
    ) -> bool {
        let mut change =
            internal.require(Some(inner.clone()), Some(outer.clone()), relationship, true);
        change |= constraints.require(
            None,
            Some(outer.clone()),
            relationship.multiply_time(dep_ty.relationship),
            true,
        );
        let usage = relationship.usage();
        *linearity |= outer.linearity() & usage.min_linearity();
        *call_usage |= usage;
        change
    }
    fn handle_internal(
        dep: &ValId,
        dep_ty: Dependency,
        arg: &SymbolId,
        constraints: &mut Constraints,
        internal: &mut Constraints,
        linearity: &mut Linearity,
        call_usage: &mut Usage,
    ) -> Result<(), ()> {
        if constraints.is_contradiction() || internal.is_contradiction() {
            return Err(());
        }
        //TODO: think about avoiding work duplication, et al...
        let local_constraints = dep.local_constraints();
        for (left, constraint) in local_constraints.iter() {
            for (right, &relationship) in constraint.iter() {
                // Internalize references
                let left = left.as_ref();
                let right = right.as_ref();
                // Check internality
                let left_dep_ty = left.map(|left| left.fv().get(arg)).unwrap_or(Some(dep_ty));
                let right_dep_ty = right
                    .map(|right| right.fv().get(arg))
                    .unwrap_or(Some(dep_ty));
                // Rebase sides
                let left = left.unwrap_or(dep);
                let right = right.unwrap_or(dep);
                // Check directionality
                match (left_dep_ty, right_dep_ty) {
                    (Some(_), Some(_)) => internal.require(
                        Some(left.clone()),
                        Some(right.clone()),
                        relationship,
                        true,
                    ),
                    (Some(left_dep_ty), None) => Self::handle_cross(
                        left,
                        right,
                        relationship,
                        left_dep_ty,
                        constraints,
                        internal,
                        linearity,
                        call_usage,
                    ),
                    (None, Some(right_dep_ty)) => Self::handle_cross(
                        right,
                        left,
                        relationship.flip(),
                        right_dep_ty.flip(),
                        constraints,
                        internal,
                        linearity,
                        call_usage,
                    ),
                    (None, None) => constraints.require(
                        Some(left.clone()),
                        Some(right.clone()),
                        relationship,
                        true,
                    ),
                };
                // Check inconsistency
                if constraints.is_contradiction() || internal.is_contradiction() {
                    return Err(());
                }
            }
        }
        Ok(())
    }
    /// Compute the constraints of a lambda function, returning an error on contradiction
    #[inline]
    fn compute_constraints(
        arg: &SymbolId,
        result: &ValId,
    ) -> Result<(Linearity, Usage, Constraints, Constraints), ()> {
        let mut internal = Constraints::default();
        let mut constraints = Constraints::default();
        let mut linearity = Linearity::default();
        let mut call_usage = Usage::default();

        // Accumulate dependencies and associated constraints
        visit_deps(
            result,
            |value| value.fv().get(arg),
            |dep, dep_ty| {
                if let Some(dep_ty) = dep_ty {
                    Self::handle_internal(
                        dep,
                        dep_ty,
                        arg,
                        &mut constraints,
                        &mut internal,
                        &mut linearity,
                        &mut call_usage,
                    )
                } else {
                    Ok(())
                }
            },
        )?;

        // Check dependencies for usage (includes checking argument usage!)
        visit_deps(
            result,
            |value| value.fv().get(arg),
            |dep, dep_ty| {
                if dep_ty.is_some()
                    && dep.as_ptr() != result.as_ptr()
                    && dep != arg
                    && internal.constraint(dep.to_opt()).usage().unobserved
                {
                    Err(())
                } else {
                    Ok(())
                }
            },
        )?;

        // Perform a cycle check
        constraints.cycle_check(&arg, &result);

        // Harmonize contradictions
        if internal.is_contradiction() || constraints.is_contradiction() {
            Err(())
        } else {
            Ok((linearity, call_usage, internal, constraints))
        }
    }
    /// Make the constraints of this lambda function
    #[inline]
    fn make_constraints(
        arg: &SymbolId,
        result: &ValId,
    ) -> (FunctionalLinearity, SymbolSet, Constraints, Constraints) {
        // Compute free-variable set
        let mut fv = arg.def_fv().union(result.fv());
        let dependency = fv.remove(&arg);

        if let Some(dependency) = dependency {
            // Compute constraints
            let constraints = Self::compute_constraints(arg, result);
            match constraints {
                Ok((linearity, call_usage, internal, constraints)) => (
                    FunctionalLinearity::new(dependency, linearity, call_usage),
                    fv,
                    internal,
                    constraints,
                ),
                Err(()) => (
                    FunctionalLinearity::CONTRADICTION,
                    fv,
                    Constraints::Contradiction,
                    Constraints::Contradiction,
                ),
            }
        } else if arg == result {
            // Identity case
            (
                FunctionalLinearity::id(arg.ty_linearity()),
                fv,
                Constraints::default(),
                Constraints::default(),
            )
        } else {
            // Constant case
            (
                FunctionalLinearity::const_fn(result.linearity()),
                fv,
                Constraints::default(),
                Constraints::dependency(result.clone()),
            )
        }
    }
    /// Get the hasher used for lambda functions
    #[inline]
    pub fn get_hasher() -> AHasher {
        AHasher::new_with_keys(4, 5)
    }
    /// Get the relationship between this lambda function's argument and it's result, if any
    pub fn relationship(&self) -> Option<Dependency> {
        self.result.fv().get(&self.arg)
    }
}

impl Value for Lambda {
    #[inline]
    fn ty(&self) -> &ValId {
        &self.ty
    }
    #[inline]
    fn into_enum(self) -> ValueEnum {
        ValueEnum::Lambda(self)
    }
    #[inline]
    fn code(&self) -> u64 {
        self.code
    }
    #[inline]
    fn fv(&self) -> &SymbolSet {
        &self.fv
    }
    #[inline]
    fn local_constraints(&self) -> &Constraints {
        &self.constraints
    }
    fn eval_in_ctx(&self, ctx: &mut EvalCtx) -> Option<ValId> {
        if ctx.is_empty() {
            // We always treat lambdas as normalized, for now
            return None;
        }
        let new_arg = self.arg.new_in_ctx(ctx);
        let mut ctx_tmp;
        let (arg, ctx) = if let Some(arg) = new_arg {
            if self.is_const_fn() {
                (Some(arg), ctx)
            } else {
                ctx_tmp = ctx.added_unchecked(self.arg.clone(), arg.clone().into_valid())
                    .expect("Adding a new symbol with a guaranteed new definition always results in a change");
                (Some(arg), &mut ctx_tmp)
            }
        } else if let Some(removed) = ctx.removed(&self.arg) {
            ctx_tmp = removed;
            (None, &mut ctx_tmp)
        } else {
            (None, ctx)
        };
        let result = self.result().eval_in_ctx(ctx);
        let (arg, result) = match (arg, result) {
            (None, None) => return None,
            (Some(arg), None) => (arg, self.result.clone()),
            (None, Some(result)) => (self.arg.clone(), result),
            (Some(arg), Some(result)) => (arg, result),
        };
        let lambda = Lambda::try_new(arg, result)
            .expect("Substituted lambda construction should never fail");
        Some(lambda.into_valid())
    }
    fn try_apply_in_ctx(&self, arg: &ValId, ctx: &mut EvalCtx) -> Result<Application, Error> {
        let mut ctx_tmp;
        let (_match, ctx_ref) = if !self.is_const_fn() {
            let (match_, c) = ctx.added(self.arg.clone(), arg.clone())?;
            if let Some(c) = c {
                ctx_tmp = c;
                (match_, &mut ctx_tmp)
            } else {
                (match_, ctx)
            }
        } else {
            let match_ = self.arg.match_symbol(arg)?;
            (match_, ctx)
        };
        let result = self
            .result
            .eval_in_ctx(ctx_ref)
            .unwrap_or_else(|| self.result.clone());
        Ok(Application::Concrete(result))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn basic_boolean_constant_properties() {
        let unary_ty = Pi::unary(
            Bool.into_valid(),
            FunctionalLinearity::const_fn(Linearity::NONLINEAR),
        )
        .unwrap()
        .into_valid();
        for r in [true, false].iter() {
            let rv = r.into_valid();
            let lambda = Lambda::constant(Bool.into_valid(), rv.clone())
                .unwrap()
                .into_valid();
            for b in [true, false].iter() {
                let bv = b.into_valid();
                assert_eq!(lambda.apply(&bv).unwrap(), r.into_valid());
                let sexpr = Sexpr::try_new(lambda.clone(), bv).unwrap();
                assert_eq!(sexpr.ty(), &*BOOL);
                assert_eq!(sexpr.normalized().unwrap(), &rv);
            }
            assert_eq!(lambda.apply(&*NAT), Err(Error::TypeMismatch));
            assert_eq!(*lambda.ty(), unary_ty);
        }
    }
    #[test]
    fn basic_boolean_identity_properties() {
        let unary_ty = Pi::unary(Bool.into_valid(), FunctionalLinearity::USED)
            .unwrap()
            .into_valid();
        let id = Lambda::id(Bool.into_valid()).unwrap();
        assert_eq!(*id.ty(), unary_ty);
        for b in [true, false].iter() {
            let bv = b.into_valid();
            assert_eq!(id.apply(&bv).unwrap(), bv);
        }
        assert_eq!(id.apply(&*NAT), Err(Error::TypeMismatch))
    }
    #[test]
    fn polymorphic_identity() {
        let ty = SymbolId::param(SET.clone()).unwrap();
        let ty_val = Symbol::from(ty.clone()).into_valid();
        let specific_id = Lambda::id(ty_val).unwrap().into_valid();
        let poly_id = Lambda::try_new(ty, specific_id).unwrap().into_valid();
        let bool_id = poly_id.apply(&*BOOL).unwrap();
        for b in [true, false].iter() {
            let bv = b.into_valid();
            assert_eq!(bool_id.apply(&bv).unwrap(), bv);
        }
        assert_eq!(bool_id.apply(&*NAT), Err(Error::TypeMismatch))
    }
    #[test]
    fn higher_order_function() {
        let unary_ty = Pi::unary(Bool.into_valid(), FunctionalLinearity::USED)
            .unwrap()
            .into_valid();
        let abs_f = SymbolId::param(unary_ty.clone()).unwrap();
        let abs_f_v = Symbol::from(abs_f.clone()).into_valid();
        debug_assert_eq!(*abs_f_v.ty(), unary_ty);
        let f_true = Sexpr::try_new(abs_f_v, true.into_valid())
            .unwrap()
            .into_valid();
        debug_assert_eq!(f_true.ty(), &*BOOL);
        let eval_true = Lambda::try_new(abs_f, f_true).unwrap().into_valid();
        let bool_id = Lambda::id(BOOL.clone()).unwrap().into_valid();
        assert_eq!(eval_true.apply(&bool_id).unwrap().ty(), &*BOOL);
        assert_eq!(eval_true.apply_norm(&bool_id), Ok(TRUE.clone()));
    }
    #[test]
    fn swap_bool() {
        let b = &*BOOL;
        let x = SymbolId::param(b.clone()).unwrap();
        let y = SymbolId::param(b.clone()).unwrap();
        let xv = x.clone().into_valid();
        let cx = Lambda::try_new(y, xv).unwrap();
        let cx = cx.into_valid();
        let sw = Lambda::try_new(x, cx).unwrap();
        let sw = sw.into_valid();
        for x in [true, false].iter() {
            for y in [true, false].iter() {
                let xv = x.into_valid();
                let yv = y.into_valid();
                let swx = Sexpr::try_new(sw.clone(), xv.clone()).unwrap();
                let swxy = Sexpr::try_new(swx.into_valid(), yv).unwrap();
                assert_eq!(swxy.normalized(), Some(&xv));
            }
        }
    }
    #[test]
    fn basic_natural_identity_properties() {
        let nat = &*NAT;
        let unary_ty = Pi::unary(nat.clone(), FunctionalLinearity::USED)
            .unwrap()
            .into_valid();
        let i = Lambda::id(nat.clone()).unwrap();
        assert_eq!(*i.ty(), unary_ty);
    }
}